package com.example.taobaou.presenter.impl;

import com.example.taobaou.model.Api;
import com.example.taobaou.model.domain.Historys;
import com.example.taobaou.model.domain.SearchRecommend;
import com.example.taobaou.model.domain.SearchResult;
import com.example.taobaou.presenter.ISearchPresenter;
import com.example.taobaou.presenter.ISelectedPagePresenter;
import com.example.taobaou.utils.JsonCacheUtils;
import com.example.taobaou.utils.LogUtils;
import com.example.taobaou.utils.RetrofitManager;
import com.example.taobaou.view.ISearchPageCallBack;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class SearchPresenter implements ISearchPresenter {

    private final Retrofit retrofit;
    private final Api api;
    private ISearchPageCallBack mSearchPageCallback = null;
    private String mCorrentKeyWord = null;
    public static final int DEFAULT_HISTORY_SIZE = 10;
    private int historysMaxSize = DEFAULT_HISTORY_SIZE;
    private final JsonCacheUtils jsoncacheutils;

    public SearchPresenter() {

        retrofit = RetrofitManager.getInstance().getRetrofit();
        api = retrofit.create(Api.class);
        jsoncacheutils = JsonCacheUtils.getInstance();

    }

    public static final String KEY_HISTORY = "key_history";

    /**
     * 添加历史记录
     *
     * @param history
     */
    private void saveHistories(String history) {
        LogUtils.d(SearchPresenter.this,"历史记录" +history);
        Historys historys = jsoncacheutils.getValue(KEY_HISTORY, Historys.class);
        //如果已经有当前搜索词，就删掉然后再添加
        List<String> historyList = null;
        if (historys != null && historys.getHistorys() != null) {
            historyList = historys.getHistorys();
            if (historyList.contains(history)) {
                historyList.remove(history);
            }
        }
        //去重完成
        //处理没有数据的情况
        if (historyList == null) {
            historyList = new ArrayList<>();
        }
        if (historys == null) {
            historys = new Historys();
        }
        LogUtils.d(SearchPresenter.this,"添加历史记录" +historyList);
        historys.setHistorys(historyList);
        //对个数进行限制
        if (historyList.size() > historysMaxSize) {
            historyList = historyList.subList(0, historysMaxSize);
        }
        //添加历史记录
        historyList.add(history);
        //保存记录
        jsoncacheutils.saveCache(KEY_HISTORY, historys);


    }

    @Override
    public void getHistories() {
        Historys histories = jsoncacheutils.getValue(KEY_HISTORY, Historys.class);
        if (mSearchPageCallback != null) {
            mSearchPageCallback.onHistoriesLoaded(histories);
        }

    }

    @Override
    public void deletedHistories() {
        jsoncacheutils.delCache(KEY_HISTORY);
        mSearchPageCallback.onHistoriesDeleted();
    }

    public static final int DEFAULT_PAGE = 0;
    /**
     * 搜索加载的当前页，默认0也就是第一页
     */
    private int mCurrentPage = DEFAULT_PAGE;

    @Override
    public void doSearch(String keyWord) {
        if (mCorrentKeyWord == null || !mCorrentKeyWord.equals(keyWord)) {
            this.saveHistories(keyWord);
            this.mCorrentKeyWord = keyWord;
        }

        if (mSearchPageCallback != null) {
            mSearchPageCallback.onLoading();
        }
        Call<SearchResult> task = api.doSearch(mCurrentPage, keyWord);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                //搜索成功
                int code = response.code();
                LogUtils.d(SearchPresenter.this, "doSearch------------------------------->" + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    handleSearckResult(response.body());
                } else {
                    onError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                onError();
            }
        });


    }

    private void handleSearckResult(SearchResult result) {
        if (mSearchPageCallback != null) {
            if (isResultEmpty(result)) {
                mSearchPageCallback.onEmpty();
            } else {
                mSearchPageCallback.onSearchSuccess(result);
            }
        }
    }

    private void onError() {

        if (mSearchPageCallback != null) {
            mSearchPageCallback.onNatworkError();
        }
    }

    @Override
    public void reSesarch() {

        if (mCorrentKeyWord == null) {
            if (mSearchPageCallback != null) {

                mSearchPageCallback.onEmpty();
            }
        } else {
            //如果搜索词不为空可以重新搜索
            this.doSearch(mCorrentKeyWord);
        }

    }

    @Override
    public void onLoaderMore() {
        mCurrentPage++;
        if (mCorrentKeyWord != null) {
            doSearchMore();
        } else {
            mSearchPageCallback.onEmpty();
            mCurrentPage--;
        }
    }

    private void doSearchMore() {
        Call<SearchResult> task = api.doSearch(mCurrentPage, mCorrentKeyWord);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                if (code == HttpURLConnection.HTTP_OK) {
                    handleSearcMorekResult(response.body());
                } else {
                    onLoaderMoreError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                onLoaderMoreError();
            }
        });
    }

    private void handleSearcMorekResult(SearchResult body) {
        if (mSearchPageCallback != null) {
            if (isResultEmpty(body)) {
                mSearchPageCallback.onLoadMoreEmpty();
            } else {
                mSearchPageCallback.onLoadedMore(body);
            }
        }
    }

    /**
     * 加载更多失败
     */
    private void onLoaderMoreError() {
        mCurrentPage--;
        if (mSearchPageCallback != null) {
            mSearchPageCallback.onLoadedMoreError();
        }

    }

    @Override
    public void getRecommendWords() {
        Call<SearchRecommend> recommend = api.getRecommend();
        recommend.enqueue(new Callback<SearchRecommend>() {
            @Override
            public void onResponse(Call<SearchRecommend> call, Response<SearchRecommend> response) {
                int code = response.code();
                LogUtils.d(SearchPresenter.this, "getRecommendWords------------------------->" + code);

                if (code == HttpURLConnection.HTTP_OK) {
                    //请求成功
                    if (mSearchPageCallback != null) {
                        mSearchPageCallback.onRecommendWordsLoaded(response.body().getData());
                    }

                } else {
                    LogUtils.d(SearchPresenter.this, " Throwable------------------------->");
                    onError();
                }
            }

            @Override
            public void onFailure(Call<SearchRecommend> call, Throwable t) {
                LogUtils.d(SearchPresenter.this, "getRecommendWords  Throwable------------------------->" + t);
                onError();
            }
        });
    }

    private boolean isResultEmpty(SearchResult result) {

        try {
            return result == null || result.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data().size() == 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void registerViewCallback(ISearchPageCallBack callback) {
        this.mSearchPageCallback = callback;
    }

    @Override
    public void unregisiterViewCallback(ISearchPageCallBack callback) {
        this.mSearchPageCallback = null;
    }
}
